package com.jbwz.web.common.exception;

import com.jbwz.web.common.res.IResponseCodeEnum;
import com.jbwz.web.common.res.ResponseCodeBase;
import com.jbwz.web.common.res.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;

@Slf4j
@ControllerAdvice
public class GlobalException {
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseJson bizExceptionHandler(HttpServletRequest req, BusinessException e) {
        IResponseCodeEnum resEnum = e.getResEnum();
        log.error("发生业务异常！原因：{}", resEnum.getMsg());
        return ResponseJson.fail(resEnum);
    }

    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    @ResponseBody()
    public ResponseJson bindException(HttpServletRequest req, Exception e) {
        log.error("参数错误:", e);
        return ResponseJson.fail(ResponseCodeBase.validFailed);
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResponseJson exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！原因:", e);
        return ResponseJson.error();
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseJson exceptionHandler(HttpServletRequest req, Exception e) {
        log.error("未知异常！原因:", e);
        return ResponseJson.error();
    }
}
